﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            divInfo.InnerHtml = MyFunction.getXSLT(Server.MapPath("XmlFiles/Login.xml"), Server.MapPath("XmlFiles/LoginPage.xslt"));

            HttpCookie cookie = Request.Cookies["Acount"];
            if (cookie == null)
            {
                cookie = new HttpCookie("Acount");
                cookie.Expires = DateTime.Now.AddDays(1);
                cookie["Failed"] = "0";
                Response.Cookies.Add(cookie);
            }
            int fail = int.Parse(cookie["Failed"]);
            if ((fail >= 3)&&(!CustomValidator1.Enabled))
            {
                divCapcha.Style.Remove(HtmlTextWriterStyle.Display);
                divCapcha.Style.Add(HtmlTextWriterStyle.Display, "block");
                CustomValidator1.Enabled = true;
            }
            OpenIdRelyingParty openid = new OpenIdRelyingParty();
            var str = openid.GetResponse();
            if (str != null)
            {
              
                switch (str.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        //NotLoggedIn.Visible = false;
                         var fetch = str.GetExtension<FetchResponse>();
                         string email = "";
                         if (fetch != null)
                         {
                            email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                            email = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName);
                            email = fetch.GetAttributeValue(WellKnownAttributes.Company.CompanyName);
                            email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                            Session["OpenID"] = email;
                        }
                        //Session["OpenID"] = str.ClaimedIdentifier.ToString();
                        Response.Redirect("Home.aspx");
                        break;
                    case AuthenticationStatus.Canceled:
                        break;
                    case AuthenticationStatus.Failed:
                        break;
                }
            }
                
        }
    }   
    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (tbMaAnToan.Value.ToLower() == Session["capcha"].ToString())
            args.IsValid = true;
        else
            args.IsValid = false;
    }
    public void alert(string text)
    {
        System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
        if (page != null)
        {
            //if (confirm("Are you sure you want to continue?")) {. . .
            //var name = prompt("Please enter your name:","Stephen");
            //if (!name) name = 'Hey You!';
            //error = error.Replace("'", "\'");
            System.Web.UI.ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + text + "');", true);
        }
    }
    protected void LinkButton1_Click1(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["Acount"];
        if (!Page.IsValid)
        {
            int fail = int.Parse(cookie["Failed"]);
            cookie["Failed"] = (fail += 1).ToString();
            Response.Cookies.Add(cookie);
            if (fail == 3)
            {
                divCapcha.Style.Remove(HtmlTextWriterStyle.Display);
                divCapcha.Style.Add(HtmlTextWriterStyle.Display, "block");
                CustomValidator1.Enabled = true;
            }
        }
        else
        {
            cookie["Failed"] = "0";
            Response.Cookies.Add(cookie);
            if (rememberme.Checked)
            {
                cookie["tendangnhap"] = tbTenDangNhap.Value;
            }
            TaiKhoan acount = DBAccess.layTK(tbTenDangNhap.Value, MyFunction.MahoaMatKhau(tbMatKhau.Value));
            Session["TaiKhoan"] = acount;
            Response.Redirect("MyPage.aspx");
        }
    }
    protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if ((DBAccess.ktTaiKhoan(tbTenDangNhap.Value, MyFunction.MahoaMatKhau(tbMatKhau.Value)) < 1))
            args.IsValid = false;
        else
            args.IsValid = true;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ImageButton btn = (ImageButton)sender;
            string str = btn.CommandArgument.ToString();
            OpenIdRelyingParty openID = new OpenIdRelyingParty();
            IAuthenticationRequest request = openID.CreateRequest(str);
            var fetch = new FetchRequest();
            fetch.Attributes.AddRequired(DotNetOpenAuth.OpenId.Extensions.AttributeExchange.WellKnownAttributes.Contact.Email);
            fetch.Attributes.AddRequired(DotNetOpenAuth.OpenId.Extensions.AttributeExchange.WellKnownAttributes.Contact.HomeAddress.City);
            fetch.Attributes.AddRequired(DotNetOpenAuth.OpenId.Extensions.AttributeExchange.WellKnownAttributes.Contact.HomeAddress.Country);
            fetch.Attributes.AddRequired(DotNetOpenAuth.OpenId.Extensions.AttributeExchange.WellKnownAttributes.Name.FullName);
            fetch.Attributes.AddRequired(DotNetOpenAuth.OpenId.Extensions.AttributeExchange.WellKnownAttributes.Company.CompanyName);
            request.AddExtension(fetch);
            //request.AddExtension(new DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.ClaimsRequest
            //{
            //    Country = DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.DemandLevel.Request,
            //    Email = DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.DemandLevel.Request,
            //    Gender = DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.DemandLevel.Require,
            //    PostalCode = DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.DemandLevel.Require,
            //    TimeZone = DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.DemandLevel.Require,
            //}
            //);
            //var b = new UriBuilder(Request.Url)
            //{
            //    Query = ""
            //};
            //var req = openID.CreateRequest(str, b.Uri, b.Uri);
            request.RedirectToProvider();
        }
        catch (System.ServiceModel.ProtocolException ex) { }
    }
}